<template>
  <div class="card-list">
    <a-page-header title="IC卡列表" @back="() => $router.back()">
      <template #extra>
        <a-button type="primary" ghost @click="addICCard()">
          <template #icon>
            <PlusOutlined />
          </template>
          添加IC卡
        </a-button>
      </template>
    </a-page-header>
    <div class="content">
      <div class="search-box">
        <a-form>
          <a-row :gutter="24">
            <a-col :xs="24" :md="6">
              <a-form-item label="业户">
                <a-select
                  v-model:value="searchForm.owner_id"
                  placeholder="请选择业户"
                  :options="ownerList"
                  allowClear
                  @change="handleSeachChange('owner')"
                ></a-select>
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="6" v-if="searchForm.owner_id">
              <a-form-item label="用户姓名">
                <a-select
                  v-model:value="searchForm.user_id"
                  placeholder="请选择用户姓名"
                  :options="userList"
                  allowClear
                  @change="getDataList(1)"
                ></a-select>
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="6">
              <a-form-item label="IC卡号">
                <a-input
                  v-model:value="searchForm.ic_card"
                  placeholder="请输入IC卡号"
                />
                <template #extra>
                  <!-- <a-space> -->
                  <a-badge
                    status="success"
                    text="RFID读卡已启动"
                    v-if="connected"
                  />
                  <a-badge status="warning" text="RFID读卡未启动" v-else />
                  <a-tooltip>
                    <template #title>
                      <span>重新启动</span>
                    </template>
                    <a-button type="link" @click="initICJS" class="ml-10">
                      <template #icon>
                        <RedoOutlined />
                      </template>
                    </a-button>
                  </a-tooltip>
                  <a-tooltip>
                    <template #title>
                      <span>下载插件</span>
                    </template>
                    <a-button type="link" @click="downloadRFID">
                      <template #icon> <DownloadOutlined /> </template>
                    </a-button>
                  </a-tooltip>
                  <!-- </a-space> -->
                </template>
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="6">
              <a-space>
                <a-button type="primary" @click="getDataList(1)">搜索</a-button>
                <a-button @click="resetSearch">重置</a-button>
              </a-space>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-table
        :columns="columns"
        :dataSource="dataList"
        :pagination="pagination"
        @change="handleTableChange"
        rowKey="id"
      >
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'status'">
            <a-badge status="success" text="正常" v-if="text == 1" />
            <a-badge status="error" text="禁止" v-else />
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="addICCard(text)"> 编辑 </a-button>
              <a-button type="link" danger @click="delICCard(text)">
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <AddICCard
      :visible="addVisible"
      :id="currentId"
      :cardReadNum="cardReadNum"
      @cancel="handleAddCancel"
      @success="handleAddSuccess"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  onBeforeUnmount,
} from "vue";
import { useRoute } from "vue-router";
import {
  PlusOutlined,
  RedoOutlined,
  DownloadOutlined,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import store from "../../../store";
import AddICCard from "./modules/AddICCard.vue";
import utils from "../../../common/utils/utils";
import { message, Modal } from "ant-design-vue";
import YOWORFIDReader from "../../../common/utils/YOWOCloudRFIDReader";

let rfidReader = null;

export default defineComponent({
  name: "ICCardList",
  components: { PlusOutlined, RedoOutlined, DownloadOutlined, AddICCard },
  setup() {
    onBeforeUnmount(() => {
      if (rfidReader) {
        rfidReader.Disconnect();
        rfidReader = null;
      }
    });

    const $route = useRoute();
    const state = reactive({
      userId: Number($route.query.userId),
      ownerId: Number($route.query.ownerId),
      dataList: [],
      page: 1,
      pageSize: 20,
      total: 0,
      ownerList: [],
      userList: [],
      addVisible: false,
      currentId: 0,
      connected: false,
      cardReadNum: "",
    });

    const searchForm = reactive({
      owner_id: undefined,
      user_id: undefined,
      ic_card: "",
    });

    const handleSeachChange = (type) => {
      if (type === "owner") {
        // 切换租客
        searchForm.user_id = undefined;
        store
          .dispatch("GetOwnerUserList", { owner_id: searchForm.owner_id })
          .then((list) => {
            state.userList = list;
          });
        getDataList(1);
        return;
      }
    };

    watch(
      () => state.cardReadNum,
      (val) => {
        console.log("cardReadNum", val);
        if (val) {
          if (!state.addVisible) {
            searchForm.owner_id = undefined;
            searchForm.user_id = undefined;
            searchForm.ic_card = state.cardReadNum;
            getDataList(1);
          }
        }
      }
    );

    const addICCard = (id) => {
      state.currentId = id || 0;
      state.cardReadNum = "";
      state.addVisible = true;
    };

    const delICCard = (id) => {
      utils.modalConfirm({
        content: `确认删除此IC卡吗？`,
        centered: true,
        onOk: () => {
          request
            .del("/village", "/user/iccard", {
              id,
              needMsg: true,
            })
            .then((res) => {
              getDataList();
              message.success(res.msg || "删除成功");
            });
        },
      });
    };

    const handleAddCancel = () => {
      state.cardReadNum = "";
      state.addVisible = false;
    };

    const handleAddSuccess = () => {
      handleAddCancel();
      getDataList(1);
    };

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.pageSize,
      showSizeChanger: true,
    }));
    const handleTableChange = (pager) => {
      state.page = pager.current;
      state.pageSize = pager.pageSize;
      getDataList();
    };

    const resetSearch = () => {
      searchForm.owner_id = undefined;
      searchForm.user_id = undefined;
      searchForm.ic_card = "";
      state.cardReadNum = "";
      getDataList(1);
    };

    const getDataList = (page) => {
      if (page) {
        state.page = page;
      }
      const params = {
        page: state.page,
        pageSize: state.pageSize,
        ...searchForm,
      };
      request.get("/village", "/user/iccard", params).then((res) => {
        state.dataList = res.list;
        state.total = res.total;
      });
    };

    const getOptionData = () => {
      store.dispatch("GetOwnerList").then((list) => {
        state.ownerList = list;
      });
      if (state.ownerId) {
        store
          .dispatch("GetOwnerUserList", { owner_id: state.ownerId })
          .then((list) => {
            state.userList = list;
          });
      }
    };

    const downloadRFID = (e) => {
      const content = e
        ? `确认下载友我科技RFIDWeb插件吗？`
        : "没有检测到友我科技RFIDWeb插件，请先下载安装！";
      utils.modalConfirm({
        content,
        centered: true,
        okText: "下载",
        onOk: () => {
          window.open(
            `${location.origin}/public_web/static/YOWOReader/RFIDReaderCloudForWebClient.exe`
          );
        },
      });
    };

    const rfidGetCardReady = () => {
      rfidReader.onResult((resultdata) => {
        console.log("resultdata", resultdata);
        switch (resultdata.FunctionID) {
          case 14:
            // 已经连上设备
            rfidReader.Repeat = 1;
            rfidReader.HaltAfterSuccess = 1;
            rfidReader.RequestTypeACardNo(1, 0);
            state.connected = true;
            break;
          case 0:
            if (resultdata.Result > 0) {
              // 获取到了卡号
              state.cardReadNum = String(resultdata.strData);
            }
            break;
          default:
            state.connected = false;
            break;
        }
      });
    };

    const initICJS = () => {
      rfidReader = YOWORFIDReader.createNew();
      const connectResult = rfidReader.TryConnect();
      if (connectResult == 1) {
        rfidGetCardReady();
      } else if (connectResult == -1) {
        message.error("浏览器不支持，请更换浏览器后重试！");
      } else if (connectResult == 0) {
        downloadRFID();
      }
    };

    const init = () => {
      searchForm.owner_id = state.ownerId || undefined;
      searchForm.user_id = state.userId || undefined;
      getDataList();
      getOptionData();
      initICJS();
    };
    init();

    return {
      columns,
      searchForm,
      pagination,
      ...toRefs(state),
      getDataList,
      addICCard,
      handleSeachChange,
      handleAddCancel,
      handleAddSuccess,
      delICCard,
      handleTableChange,
      initICJS,
      resetSearch,
      downloadRFID,
    };
  },
});
const columns = [
  {
    title: "楼宇",
    dataIndex: "build_name",
    key: "build_name",
  },
  {
    title: "业户",
    dataIndex: "owner_name",
    key: "owner_name",
  },
  {
    title: "用户姓名",
    dataIndex: "user_name",
    key: "user_name",
  },
  {
    title: "用户手机号",
    dataIndex: "user_phone",
    key: "user_phone",
  },
  {
    title: "IC卡号",
    dataIndex: "ic_card",
    key: "ic_card",
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
  },
];
</script>

<style lang="less" scoped>
.card-list {
  background: #fff;
  min-height: 100%;
  .content {
    padding: 20px;
    .search-box {
      margin-bottom: 10px;
    }
  }
}
</style>
